package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id){
        return  spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     * @param goods
     */
    @Override
    @Transactional  //添加事务
    public void add(Goods goods){
        //1.添加spu
        Spu spu = goods.getSpu();
        //1.1设置分布式id
        long spuId = idWorker.nextId();
        spu.setId(String.valueOf(spuId));
        //1.2设置删除状态
        spu.setIsDelete("0");
        //1.3设置上架状态
        spu.setIsMarketable("0");
        //1.4设置审核状态
        spu.setStatus("0");
        //添加spu
        spuMapper.insertSelective(spu);

        //2.添加sku集合
        this.saveSkuList(goods);


    }

    //封装添加sku数据的方法
    private void saveSkuList(Goods goods) {
        //获取spu对象
        Spu spu = goods.getSpu();

        //查询分类对象
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

        //查询品牌对象
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());

        //设置品牌与分类的关联信息
            //查询关联表
            CategoryBrand categoryBrand = new CategoryBrand();
            //设置品牌id
            categoryBrand.setBrandId(spu.getBrandId());
            //设置分类id
            categoryBrand.setCategoryId(spu.getCategory3Id());

        int count = categoryBrandMapper.selectCount(categoryBrand);
        if (count==0){
            //说明品牌与分类没有关联关系，设置关联关系
            categoryBrandMapper.insert(categoryBrand);
        }


        //1.获取sku集合
        List<Sku> skuList = goods.getSkuList();
        //2.非空判定后添加sku信息
        if (skuList!=null){
            //遍历sku集合，循环填充数据并添加到数据库中
            for (Sku sku : skuList) {
                //2.1设置sku的ID
                sku.setId(String.valueOf(idWorker.nextId()));
                //2.2设置sku的规格数据，进行非空判断
                if (StringUtils.isEmpty(sku.getSpec())){
                    sku.setSpec("{}");
                }
                //2.3设置sku的名称（spu的名称+规格）
                    //2.3.1获取spu的名称
                    String name = spu.getName();
                    //2.3.2获取spu的规格
                    Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                    //2.3.3将json转换成map,将map中的value进行名称的拼接
                    if (specMap!=null && specMap.size()>0){
                        for (String value : specMap.values()) {
                            name+=" "+value;
                        }
                    }
                    //2.3.4设置sku名称
                    sku.setName(name);
                    //2.4设置spuID
                    sku.setSpuId(spu.getId());
                    //2.5设置创建与修改时间
                    sku.setCreateTime(new Date());
                    sku.setUpdateTime(new Date());
                    //2.5设置商品分类ID
                    sku.setCategoryId(category.getId());
                    //2.5设置商品分类的名称
                    sku.setCategoryName(category.getName());
                    //2.6设置商品分类的名称
                    sku.setBrandName(brand.getName());
                    //2.6将sku添加到数据库中
                    skuMapper.insertSelective(sku);

            }
        }
    }


    /**
     * 修改
     * @param goods
     */
    @Transactional
    @Override
    public void update(Goods goods){

        //1.修改spu
        Spu spu = goods.getSpu();
        if (spu.getId()==null){
            throw new RuntimeException("spuId不存在");
        }
        spuMapper.updateByPrimaryKey(spu);

        //2.修改sku
        //2.1删除原有的sku列表
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spu.getId());
        skuMapper.deleteByExample(example);
        //2.2现有的sku列表重新添加,调用封装的saveSkuList方法
        this.saveSkuList(goods);

    }

    /**
     * 逻辑删除商品
     * @param id
     */
    @Transactional
    @Override
    public void delete(String id){
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //2.非空判断
        if (spu==null){
            throw new RuntimeException("当前商品不存在");
        }
        //3.1判断当前前商品是否处于下架状态
        if (!"0".equals(spu.getIsMarketable())){
            throw new RuntimeException("该商品未下架，请先下架该商品后再进行删除,么么哒(づ￣ 3￣)づ");
        }
        //3.2如果是处于下架状态，修改对应的标记位经行逻辑删除
        //3.2.1逻辑删除
        spu.setIsDelete("1");
        //3.2.2审核状态修改为未审核
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 物理删除商品
     * @param id
     */
    @Transactional
    @Override
    public void realDelete(String id) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //2.非空判断
        if (spu==null){
            throw new RuntimeException("当前商品不存在");
        }
        //3.判断该商品是否逻辑删除
        if (!"1".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品没有进行逻辑删除，请逻辑删除后重试");
        }
        //4.物理删除
        spuMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Spu>)spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }

    /**
     * 根据id查询商品（spu与sku列表信息）
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsById(String id) {

        //1.查询spu的信息
        Spu spu = spuMapper.selectByPrimaryKey(id);

        //2.查询sku的信息
        //2.1设置查询条件
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        //2.2根据spu进行sku列表的查询
        criteria.andEqualTo("spuId",id);
        List<Sku> skuList = skuMapper.selectByExample(example);

        //3.封装goods并返回
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);

        return goods;
    }

    /**
     * 商品审核并自动上架
     * @param id
     */
    @Transactional
    @Override
    public void audit(String id) {
        //1.查询spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //2.非空判断
        if (spu==null){
            throw new RuntimeException("当前商品不存在");
        }
        //3.1判断当前spu是否处于删除状态
        if ("1".equals(spu.getIsDelete())){
            throw new RuntimeException("当前商品处于删除状态");
        }
        //3.2如果不处于删除状态，修改审核状态为1，上下架状态为1
        spu.setStatus("1");
        spu.setIsMarketable("1");
        //4.执行修改操作
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 下架商品
     * @param id
     */
    @Transactional
    @Override
    public void pull(String id) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //2.非空判断
        if (spu==null){
            throw new RuntimeException("当前商品不存在");
        }
        //3.判断商品是否处于删除状态
        if ("1".equals(spu.getIsDelete())){
            throw new RuntimeException("当前商品处于删除状态");
        }
        //4.商品处于未删除状态时，则修改上下架状态为“已下架（0）”
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 上架商品
     * @param id
     */
    @Transactional
    @Override
    public void put(String id) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //2.非空判断
        if (spu==null){
            throw new RuntimeException("当前商品不存在");
        }
        //3.判断商品是否经过审核
        if (!"1".equals(spu.getStatus())){
            throw new RuntimeException("商品未经过审核不能上架");
        }
        //4.修改上架状态
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 还原逻辑删除的商品（恢复数据）
     * @param id
     */
    @Transactional
    @Override
    public void restore(String id) {
        //1.检查spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //2.非空判断
        if (spu==null){
            throw new RuntimeException("当前商品不存在");
        }
        //3.判断商品是否逻辑删除
        if (!"1".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品没有被删除哦");
        }
        //4.恢复数据
        //4.1设置商品状态为未删除
        spu.setIsDelete("0");
        //4.2设置商品状态为未审核
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
           	}
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
           	}
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
           	}
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
           	}
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
           	}
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
           	}
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
           	}
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
           	}
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
           	}
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andEqualTo("isMarketable",searchMap.get("isMarketable"));
           	}
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
           	}
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andEqualTo("isDelete",searchMap.get("isDelete"));
           	}
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
           	}

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
